package com.zxy.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

//@RestController
@Slf4j
public class TestController {
    @GetMapping("/test")
    public String call(){
        Entry entry = null;
        String msg = "";
        try {
//            abc 代表的是一个资源名称，可以用方法名，唯一标识
            entry = SphU.entry("abc");
//            被保护的资源，里面写的就是我们的业务代码
            log.debug("正常执行");
            msg = ("正常执行");
//            resource that need protection
        }catch (BlockException blockException){
//            被中断阻止会打印这个日志，限流

            log.debug("block");
            msg = "block";
        }catch (Throwable bizException){
//            business exception
//            如果配置了服务降级规则，需要通过这种方式才能触发降级
            Tracer.trace(bizException);
        }finally {
//            ensure finally be executed
            if (entry != null){
                entry.exit();
            }
        }
        return msg;
    }

    @PostConstruct//初始化注解
    public void init(){
        List<FlowRule> rules = new ArrayList<>();
        FlowRule rule = new FlowRule();
        rule.setResource("abc");
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // Set limit QPS to 20.
        rule.setCount(1);
        rules.add(rule);
        FlowRuleManager.loadRules(rules);
    }












}
